<script setup>
import MyTable from '@/components/MyTable.vue';
import StickPopup from '@/components/StickPopup.vue';
import { ref, onMounted, computed } from 'vue';
import { Search, Operation, Close } from '@element-plus/icons-vue'
import { ElMessageBox, ElNotification } from 'element-plus';

const columns = [
    {
        title: '渠道名称',
        key: 'channelName',
        sortable: true,
        fixed: 'left' // 固定左侧
    },
    {
        title: '渠道负责人',
        key: 'channelOwner',
        filterable: true
    },
    {
        title: '下次联系时间',
        key: 'nextContactTime',
        sortable: true
    },
    {
        title: '渠道状态',
        key: 'channelStatus',
        filterable: true
    },
    {
        title: '上次联系时间',
        key: 'lastContactTime',
        sortable: true
    },
    {
        title: '渠道提交人',
        key: 'channelSubmitter',
        filterable: true
    },
    {
        title: '创建时间',
        key: 'createTime',
        sortable: true
    },
    {
        title: '所属部门',
        key: 'department'
    }
];

// 数据状态
const allData = ref([]);
const recycleBin = ref([]); // 回收站数据
const loading = ref(true)
const searchText = ref('')
const activeName = ref('first')

// 编辑侧边栏相关
const editPanelVisible = ref(false);
const editForm = ref({});
const currentEditIndex = ref(-1);

// 筛选表单
const filterForm = ref({
    channelOwner: '',
    channelSubmitter: '',
    channelStatus: '',
    nextContactTimeRange: [],
    department: '',
    lastContactTimeRange: [],
    createTimeRange: []
})

// 筛选选项数据
const filterOptions = ref({
    channelOwner: ['张三', '李四', '王五', '赵六', '孙七', '周八'],
    channelSubmitter: ['李四', '赵六', '孙八', '吴九', '郑十'],
    channelStatus: ['正常', '无效'],
    department: ['市场一部', '市场二部', '市场三部', '渠道部', '销售部']
})

// 从localStorage加载回收站数据
const loadRecycleBin = () => {
    const saved = localStorage.getItem('channelRecycleBin');
    if (saved) {
        recycleBin.value = JSON.parse(saved);
    }
};

// 保存回收站数据到localStorage
const saveRecycleBin = () => {
    localStorage.setItem('channelRecycleBin', JSON.stringify(recycleBin.value));
};

// 打开编辑侧边栏
const openEditDialog = (row) => {
    const index = allData.value.findIndex(item => 
        item.channelName === row.channelName && item.createTime === row.createTime
    );
    
    if (index !== -1) {
        currentEditIndex.value = index;
        editForm.value = { ...row };
        editPanelVisible.value = true;
        // 阻止页面滚动
        document.body.style.overflow = 'hidden';
    }
};

// 保存编辑
const saveEdit = () => {
    if (currentEditIndex.value !== -1) {
        // 更新数据
        allData.value[currentEditIndex.value] = { ...editForm.value };
        
        ElNotification.success({
            title: '修改成功',
            message: '渠道信息已更新',
        });
        
        closeEditDialog();
    }
};

// 关闭编辑侧边栏
const closeEditDialog = () => {
    editPanelVisible.value = false;
    editForm.value = {};
    currentEditIndex.value = -1;
    // 恢复页面滚动
    document.body.style.overflow = '';
};

const deleteClue = (row) => {
    ElMessageBox.confirm(
        `确定要删除渠道"${row.channelName}"吗？`,
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 复制要删除的数据并添加删除时间
        const itemToDelete = {
            ...row,
            deletedTime: new Date().toISOString() // 记录删除时间
        };
        
        // 从原数据中移除
        allData.value = allData.value.filter(item => 
            !(item.channelName === row.channelName && item.createTime === row.createTime)
        );
        
        // 添加到回收站
        recycleBin.value.push(itemToDelete);
        saveRecycleBin(); // 保存到本地存储
        
        ElNotification.success({
            title: '删除成功',
            message: '渠道已移至回收站',
        });
    }).catch(() => {
        // 取消删除
    });
};

// 计算属性：根据筛选条件过滤数据
const filteredData = computed(() => {
    let data = [...allData.value];
    
    // 搜索框筛选
    if (searchText.value) {
        const keyword = searchText.value.toLowerCase();
        data = data.filter(item => 
            item.channelName.toLowerCase().includes(keyword) || 
            item.channelOwner.toLowerCase().includes(keyword) ||
            item.channelSubmitter.toLowerCase().includes(keyword)
        );
    }
    
    // 高级筛选条件
    if (filterForm.value.channelOwner) {
        data = data.filter(item => 
            item.channelOwner === filterForm.value.channelOwner
        );
    }
    
    if (filterForm.value.channelSubmitter) {
        data = data.filter(item => 
            item.channelSubmitter === filterForm.value.channelSubmitter
        );
    }
    
    if (filterForm.value.channelStatus) {
        data = data.filter(item => 
            item.channelStatus === filterForm.value.channelStatus
        );
    }
    
    if (filterForm.value.department) {
        data = data.filter(item => 
            item.department === filterForm.value.department
        );
    }
    
    // 日期范围筛选
    if (filterForm.value.nextContactTimeRange && filterForm.value.nextContactTimeRange.length === 2) {
        const [start, end] = filterForm.value.nextContactTimeRange;
        data = data.filter(item => {
            if (!item.nextContactTime || item.nextContactTime === '-') return false;
            const itemDate = new Date(item.nextContactTime.split(' ')[0]);
            return itemDate >= new Date(start) && itemDate <= new Date(end);
        });
    }
    
    if (filterForm.value.lastContactTimeRange && filterForm.value.lastContactTimeRange.length === 2) {
        const [start, end] = filterForm.value.lastContactTimeRange;
        data = data.filter(item => {
            if (!item.lastContactTime || item.lastContactTime === '-') return false;
            const itemDate = new Date(item.lastContactTime.split(' ')[0]);
            return itemDate >= new Date(start) && itemDate <= new Date(end);
        });
    }
    
    if (filterForm.value.createTimeRange && filterForm.value.createTimeRange.length === 2) {
        const [start, end] = filterForm.value.createTimeRange;
        data = data.filter(item => {
            if (!item.createTime || item.createTime === '-') return false;
            const itemDate = new Date(item.createTime.split(' ')[0]);
            return itemDate >= new Date(start) && itemDate <= new Date(end);
        });
    }
    
    return data;
});

// 应用筛选条件
const applyFilter = () => {
    loading.value = true;
    setTimeout(() => {
        loading.value = false;
    }, 500);
}

// 重置筛选条件
const resetFilter = () => {
    filterForm.value = {
        channelOwner: '',
        channelSubmitter: '',
        channelStatus: '',
        nextContactTimeRange: [],
        department: '',
        lastContactTimeRange: [],
        createTimeRange: []
    };
    applyFilter();
}

const handleClick = (tab, event) => {
    console.log(tab, event);
    loading.value = true;
    setTimeout(() => {
        loading.value = false;
    }, 500);
}

// 获取所有渠道数据
const getAllChannelData = () => {
    return [
        {
            channelName: '线上广告渠道',
            channelOwner: '张三',
            nextContactTime: '2023-10-20 10:00',
            channelStatus: '正常',
            lastContactTime: '2023-10-15 14:30',
            channelSubmitter: '李四',
            createTime: '2023-10-05 08:30',
            department: '市场一部'
        },
        {
            channelName: '合作伙伴推荐',
            channelOwner: '李四',
            nextContactTime: '2023-10-25 14:00',
            channelStatus: '正常',
            lastContactTime: '2023-10-18 16:45',
            channelSubmitter: '赵六',
            createTime: '2023-10-08 10:15',
            department: '市场二部'
        },
        {
            channelName: '展会获取渠道',
            channelOwner: '王五',
            nextContactTime: '2023-10-28 15:30',
            channelStatus: '正常',
            lastContactTime: '2023-10-20 09:30',
            channelSubmitter: '孙八',
            createTime: '2023-10-12 14:20',
            department: '市场三部'
        },
        {
            channelName: '官网注册渠道',
            channelOwner: '赵六',
            nextContactTime: '2023-10-22 11:00',
            channelStatus: '正常',
            lastContactTime: '2023-10-17 15:20',
            channelSubmitter: '吴九',
            createTime: '2023-10-10 09:45',
            department: '渠道部'
        },
        {
            channelName: '电话营销渠道',
            channelOwner: '孙七',
            nextContactTime: '2023-10-30 09:00',
            channelStatus: '正常',
            lastContactTime: '2023-10-25 13:15',
            channelSubmitter: '郑十',
            createTime: '2023-10-15 16:30',
            department: '销售部'
        },
        {
            channelName: '客户转介绍',
            channelOwner: '周八',
            nextContactTime: '-',
            channelStatus: '无效',
            lastContactTime: '2023-10-10 11:30',
            channelSubmitter: '李四',
            createTime: '2023-10-03 14:10',
            department: '市场一部'
        },
        {
            channelName: '社交媒体渠道',
            channelOwner: '张三',
            nextContactTime: '2023-11-05 16:00',
            channelStatus: '正常',
            lastContactTime: '2023-10-28 10:45',
            channelSubmitter: '赵六',
            createTime: '2023-10-20 08:15',
            department: '市场二部'
        },
        {
            channelName: '内容营销渠道',
            channelOwner: '王五',
            nextContactTime: '2023-11-08 14:30',
            channelStatus: '正常',
            lastContactTime: '2023-10-30 16:20',
            channelSubmitter: '孙八',
            createTime: '2023-10-25 11:40',
            department: '市场三部'
        }
    ]
}

onMounted(() => {
    loadRecycleBin(); // 加载回收站数据
    
    setTimeout(() => {
        allData.value = getAllChannelData();
        loading.value = false;
    }, 500);
})
</script>

<template>
    <div class="my-clue">
        <div class="top-filter">
            <div class="top-filter-left">
                <stick-popup>
                    <template #show>
                        <div class="top-filter-btn">
                            <div class="top-filter-btn-label">
                                筛选
                            </div>
                            <div class="top-filter-btn-icon">
                                <Operation />
                            </div>
                        </div>
                    </template>
                    <template #content>
                        <!-- 扩展筛选表单 -->
                        <div class="top-filter-form">
                            <el-form :model="filterForm" label-width="120px">
                                <el-form-item label="渠道负责人">
                                    <el-select v-model="filterForm.channelOwner" placeholder="请选择渠道负责人" clearable>
                                        <el-option 
                                            v-for="item in filterOptions.channelOwner" 
                                            :key="item" 
                                            :label="item" 
                                            :value="item"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="渠道提交人">
                                    <el-select v-model="filterForm.channelSubmitter" placeholder="请选择渠道提交人" clearable>
                                        <el-option 
                                            v-for="item in filterOptions.channelSubmitter" 
                                            :key="item" 
                                            :label="item" 
                                            :value="item"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="渠道状态">
                                    <el-select v-model="filterForm.channelStatus" placeholder="请选择渠道状态" clearable>
                                        <el-option 
                                            v-for="item in filterOptions.channelStatus" 
                                            :key="item" 
                                            :label="item" 
                                            :value="item"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="下次联系时间">
                                    <el-date-picker
                                        v-model="filterForm.nextContactTimeRange"
                                        type="daterange"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        value-format="YYYY-MM-DD"
                                        style="width: 100%"
                                    />
                                </el-form-item>
                                <el-form-item label="所属部门">
                                    <el-select v-model="filterForm.department" placeholder="请选择所属部门" clearable>
                                        <el-option 
                                            v-for="item in filterOptions.department" 
                                            :key="item" 
                                            :label="item" 
                                            :value="item"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="上次联系时间">
                                    <el-date-picker
                                        v-model="filterForm.lastContactTimeRange"
                                        type="daterange"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        value-format="YYYY-MM-DD"
                                        style="width: 100%"
                                    />
                                </el-form-item>
                                <el-form-item label="渠道创建时间">
                                    <el-date-picker
                                        v-model="filterForm.createTimeRange"
                                        type="daterange"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        value-format="YYYY-MM-DD"
                                        style="width: 100%"
                                    />
                                </el-form-item>
                            </el-form>
                        </div>
                    </template>
                    <template #footer>
                        <div class="top-filter-operate">
                            <el-button @click="resetFilter">重置</el-button>
                            <el-button type="primary" @click="applyFilter">确定</el-button>
                        </div>
                    </template>
                </stick-popup>
                <div class="top-filter-search">
                    <el-input
                        v-model="searchText"
                        placeholder="搜索渠道名称、负责人、提交人..."
                    >
                        <template #append>
                            <el-button :icon="Search" />
                        </template>
                    </el-input>
                </div>
            </div>
            <div class="top-filter-right">
                <el-button type="primary">导入渠道</el-button>
                <el-button type="primary">新渠道</el-button>
                <el-button type="primary">老渠道</el-button>
                <el-button type="primary">导出</el-button>
                <!-- 回收站入口 -->
                <el-button type="warning" @click="$router.push('/channel-recycle-bin')">
                    回收站 ({{ recycleBin.length }})
                </el-button>
            </div>
        </div>
        <div class="table-area">
            <div class="table-area-table">
                <my-table 
                    :loading="loading" 
                    :columns="columns" 
                    :dataSource="filteredData" 
                    :showIndex="true" 
                    :show-operation="true"
                    scroll-x="1200">
                    <!-- 可排序字段的筛选模板 -->
                    <template #filter-channelName>
                        <span>渠道名称</span>
                        <el-icon class="filter-icon"></el-icon>
                    </template>
                    <template #filter-nextContactTime>
                        <span>下次联系时间</span>
                        <el-icon class="filter-icon"></el-icon>
                    </template>
                    <template #filter-lastContactTime>
                        <span>上次联系时间</span>
                        <el-icon class="filter-icon"></el-icon>
                    </template>
                    <template #filter-createTime>
                        <span>创建时间</span>
                        <el-icon class="filter-icon"></el-icon>
                    </template>
                    <template #data-channelStatus="scope">
                        <el-tag :type="scope.data === '正常' ? 'success' : 'danger'">
                            {{ scope.data }}
                        </el-tag>
                    </template>
                    <template #operation="scope">
                        <el-button type="text" @click="openEditDialog(scope.row)">修改</el-button>
                        <el-button type="text" @click="deleteClue(scope.row)">删除</el-button>
                    </template>
                </my-table>
            </div>
        </div>

        <!-- 编辑侧边栏 -->
        <div class="edit-overlay" v-if="editPanelVisible" @click="closeEditDialog"></div>
        <div class="edit-panel" :class="{ 'edit-panel-visible': editPanelVisible }">
            <div class="edit-panel-header">
                <h3>修改渠道信息</h3>
                <el-button icon="Close" circle @click="closeEditDialog" />
            </div>
            <div class="edit-panel-body">
                <el-form :model="editForm" label-width="120px">
                    <!-- 第一行：渠道名称 + 渠道负责人 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="渠道名称">
                                <el-input v-model="editForm.channelName" placeholder="请输入渠道名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="渠道负责人">
                                <el-select v-model="editForm.channelOwner" placeholder="请选择渠道负责人" style="width: 100%">
                                    <el-option 
                                        v-for="item in filterOptions.channelOwner" 
                                        :key="item" 
                                        :label="item" 
                                        :value="item"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 第二行：渠道状态 + 所属部门 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="渠道状态">
                                <el-select v-model="editForm.channelStatus" placeholder="请选择渠道状态" style="width: 100%">
                                    <el-option 
                                        v-for="item in filterOptions.channelStatus" 
                                        :key="item" 
                                        :label="item" 
                                        :value="item"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属部门">
                                <el-select v-model="editForm.department" placeholder="请选择所属部门" style="width: 100%">
                                    <el-option 
                                        v-for="item in filterOptions.department" 
                                        :key="item" 
                                        :label="item" 
                                        :value="item"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 第三行：渠道提交人 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="渠道提交人">
                                <el-select v-model="editForm.channelSubmitter" placeholder="请选择渠道提交人" style="width: 100%">
                                    <el-option 
                                        v-for="item in filterOptions.channelSubmitter" 
                                        :key="item" 
                                        :label="item" 
                                        :value="item"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 第四行：下次联系时间 + 上次联系时间 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="下次联系时间">
                                <el-date-picker
                                    v-model="editForm.nextContactTime"
                                    type="datetime"
                                    placeholder="选择下次联系时间"
                                    style="width: 100%"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="上次联系时间">
                                <el-date-picker
                                    v-model="editForm.lastContactTime"
                                    type="datetime"
                                    placeholder="选择上次联系时间"
                                    style="width: 100%"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 第五行：创建时间 -->
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="创建时间">
                                <el-date-picker
                                    v-model="editForm.createTime"
                                    type="datetime"
                                    placeholder="选择创建时间"
                                    style="width: 100%"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="edit-panel-footer">
                <el-button @click="closeEditDialog">取消</el-button>
                <el-button type="primary" @click="saveEdit">保存</el-button>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.my-clue {
    width: 100%;
    height: 100%;
    background-color: rgb(239,239,239);
    overflow: auto;
    position: relative;
}
.top-filter {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    padding: 0 20px;
    box-sizing: border-box;
    position: sticky;
    top: 0;
    z-index: 9;
}
.top-filter-left {
    height: 60px;
    display: flex;
    align-items: center;
    gap: 10px;
    .top-filter-btn {
        width: 80px;
        height: 30px;
        border-radius: 5px;
        border: 1px solid #ccc;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        user-select: none;
        cursor: pointer;
        .top-filter-btn-icon {
            width: 20px;
            height: 20px;
            img {
                width: 100%;
                height: 100%;
            }
        }
    }
    .top-filter-search {
        width: 250px;
    }
}
.table-area {
    width: 94%;
    margin: 20px auto;
    box-shadow: 0 0 10px 0 #ddd;
    background-color: #fff;
    padding: 10px 20px;
    box-sizing: border-box;
    .table-area-tab {
        width: 100%;
        box-sizing: border-box;
    }
    .table-area-table {
        width: 100%;
        box-sizing: border-box;
    }
}

.top-filter-form, .top-filter-operate {
    width: 500px;
    background-color: #fff;
    max-height: 600px;
    overflow-y: auto;
}

.top-filter-form {
    padding: 10px;
}

// 表格样式优化
:deep(.el-table) {
    .el-table__fixed {
        box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
    }
    
    .el-table__fixed-right {
        box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
    }
}

// 侧边编辑面板样式
.edit-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    transition: opacity 0.3s;
}

.edit-panel {
    position: fixed;
    top: 0;
    right: -600px; /* 初始位置在右侧外部 */
    width: 600px;
    height: 100vh;
    background-color: #fff;
    z-index: 1001;
    box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
    transition: right 0.3s ease-in-out;
    display: flex;
    flex-direction: column;
}

.edit-panel-visible {
    right: 0; /* 显示时滑入 */
}

.edit-panel-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.edit-panel-body {
    flex: 1;
    padding: 20px;
    overflow-y: auto; /* 允许表单区域滚动 */
}

.edit-panel-footer {
    padding: 16px 20px;
    border-top: 1px solid #e8e8e8;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

// 表单样式调整
:deep(.el-form-item) {
    margin-bottom: 18px;
}

:deep(.el-select), :deep(.el-input), :deep(.el-date-picker) {
    width: 100%;
}
</style>